package org.tooyoung.fourone.user.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;

import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.tooyoung.fourone.MainActivity;
import org.tooyoung.fourone.R;
import org.tooyoung.fourone.user.edittextfirework.FireworkView;
import org.tooyoung.fourone.user.model.UserImformation;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.QueryListener;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.tencent.qzone.QZone;
import cn.sharesdk.wechat.friends.Wechat;

public class LoginActivity extends AppCompatActivity implements View.OnClickListener, PlatformActionListener {

    private EditText txt_username;
    private EditText txt_userpassword;
    private ImageView img_anim;
    private ImageView btn_shareQQ;
    private ImageView btn_shareWeibo;
    private ImageView btn_shareWeixin;
    private ImageView btn_shareQzon;
    private static List<UserImformation> mList;
    private FireworkView mFireworkView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ShareSDK.initSDK(this);
        Bmob.initialize(this, "1c20f8eef3a087e65f6e1012ac4307f4");
        TextView btnRegist = (TextView) findViewById(R.id.btn_register);
        TextView btnLaungh = (TextView) findViewById(R.id.btn_laungh);
        img_anim = (ImageView) findViewById(R.id.image_gift);
        txt_username = ((EditText) findViewById(R.id.userfragment_username));
        txt_userpassword = ((EditText) findViewById(R.id.userfragment_userpassword));
        btn_shareQQ = (ImageView) findViewById(R.id.btn_shareQQ);
        btn_shareWeibo = (ImageView) findViewById(R.id.btn_shareWeibo);
        btn_shareWeixin = (ImageView) findViewById(R.id.btn_shareWeixin);
        btn_shareQzon = (ImageView) findViewById(R.id.btn_shareQzon);
        btn_shareQQ.setOnClickListener(this);
        btn_shareWeibo.setOnClickListener(this);
        btn_shareWeixin.setOnClickListener(this);
        btn_shareQzon.setOnClickListener(this);
        btnLaungh.setOnClickListener(this);
        btnRegist.setOnClickListener(this);
    }

    public static List<UserImformation> getUserInformation(){
            return mList;
    }

    @Override
    protected void onResume() {
        super.onResume();
        mList = new ArrayList<>();
        BmobQuery query = new BmobQuery("UserImformation");
        query.findObjectsByTable(new QueryListener<JSONArray>() {
            @Override
            public void done(JSONArray jsonArray, BmobException e) {

                int length = jsonArray.length();
                for (int i = 0; i < length; i++) {
                    try {
                        JSONObject jsonObject = jsonArray.getJSONObject(i);
                        Gson gson = new Gson();
                        UserImformation userImformation = gson.fromJson(jsonObject.toString(), UserImformation.class);
                        mList.add(userImformation);
                    } catch (JSONException e1) {
                        e1.printStackTrace();
                    }

                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_laungh:
                //登录验证账号和密码：
                Drawable drawable = img_anim.getDrawable();
                if (drawable != null && drawable instanceof AnimationDrawable) {
                    AnimationDrawable animationDrawable = (AnimationDrawable) drawable;
                    animationDrawable.start();
                }

                final String name = txt_username.getText().toString().trim();
                String pwd = txt_userpassword.getText().toString().trim();
                EMClient.getInstance().login(name, pwd, new EMCallBack() {
                    @Override
                    public void onSuccess() {
                        EMClient client = EMClient.getInstance();
                        client.groupManager().loadAllGroups();
                        client.chatManager().loadAllConversations();
                        Log.d("user", "onSuccess: " + name);
                    }

                    @Override
                    public void onError(int i, String s) {
                        Log.d("user", "onError: " + s);
                    }

                    @Override
                    public void onProgress(int i, String s) {

                    }
                });

                checkInformation();
                break;
            case R.id.btn_register:
                Intent intent = new Intent(this, RegisterActivity.class);
                startActivity(intent);
                break;
            case R.id.btn_shareWeibo:
                Platform weibo = ShareSDK.getPlatform(SinaWeibo.NAME);
                weibo.SSOSetting(false);  //设置false表示使用SSO授权方式
                weibo.setPlatformActionListener(this); // 设置分享事件回调
                weibo.authorize();//单独授权
                weibo.showUser(null);//授权并获取用户信息
                break;
            case R.id.btn_shareQQ:
                Platform qq = ShareSDK.getPlatform(QQ.NAME);
                qq.SSOSetting(false);  //设置false表示使用SSO授权方式
                qq.setPlatformActionListener(this); // 设置分享事件回调
                qq.authorize();//单独授权
                qq.showUser(null);//授权并获取用户信息
                break;
            case R.id.btn_shareQzon:
                Platform qzon = ShareSDK.getPlatform(QZone.NAME);
                qzon.SSOSetting(false);  //设置false表示使用SSO授权方式
                qzon.setPlatformActionListener(this); // 设置分享事件回调
                qzon.authorize();//单独授权
                qzon.showUser(null);//授权并获取用户信息
                break;
            case R.id.btn_shareWeixin:
                Platform wechat = ShareSDK.getPlatform(Wechat.NAME);
                wechat.SSOSetting(false);  //设置false表示使用SSO授权方式
                wechat.setPlatformActionListener(this); // 设置分享事件回调
                wechat.authorize();//单独授权
                wechat.showUser(null);//授权并获取用户信息
                break;
        }

    }

    private void checkInformation() {
        BmobQuery query = new BmobQuery("UserImformation");
        String name = txt_username.getText().toString().trim();
        String password = txt_userpassword.getText().toString().trim();
        Log.d("USER", "checkInformation:" + "name" + name + "password" + password);
        if ("".equals(name) || "".equals(password)) {
            Toast.makeText(this, "请输入账户信息", Toast.LENGTH_SHORT).show();
            stopAnim();

        } else {
            query.addWhereEqualTo("username", name);
            query.addWhereEqualTo("userpassword", password);
            query.findObjectsByTable(new QueryListener<JSONArray>() {
                @Override
                public void done(JSONArray jsonArray, BmobException e) {
                    if (jsonArray != null) {
                        if (jsonArray.length() == 0) {
                            Toast.makeText(LoginActivity.this, "登录失败,请核对登录信息", Toast.LENGTH_SHORT).show();
                            stopAnim();
                        } else {
                            JSONObject jsonObject = null;
                            try {
                                jsonObject = jsonArray.getJSONObject(0);
                            } catch (JSONException e1) {
                                e1.printStackTrace();
                            }
                            String username = jsonObject.optString("username");
                            Toast.makeText(LoginActivity.this, "登陆成功，欢迎你:" + username, Toast.LENGTH_SHORT).show();
                            stopAnim();
                            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                            intent.putExtra("username", username);
                            startActivity(intent);
                        }
                    } else {
                        Toast.makeText(LoginActivity.this, "服务器异常，请稍后", Toast.LENGTH_SHORT).show();
                        stopAnim();
                    }
                }
            });
        }
    }

    private void stopAnim() {
        Drawable drawable = img_anim.getDrawable();
        if (drawable != null && drawable instanceof AnimationDrawable) {
            AnimationDrawable animationDrawable = (AnimationDrawable) drawable;
            if (animationDrawable.isRunning()) {
                animationDrawable.stop();
            }
        }
    }

    @Override
    public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
        Toast.makeText(this, "完成", Toast.LENGTH_SHORT).show();

    }

    @Override
    public void onError(Platform platform, int i, Throwable throwable) {
        Toast.makeText(this, "错误", Toast.LENGTH_SHORT).show();


    }

    @Override
    public void onCancel(Platform platform, int i) {
        Toast.makeText(this, "取消", Toast.LENGTH_SHORT).show();

    }
}
